﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using WarehouseManagement.BusinessLogic.BC;
using WarehouseManagement.BusinessLogic.DTO;
using WarehouseManagement.ViewModels.Merchandise;

namespace WarehouseManagement.Presenters.Merchandise
{
    public class NewEditMerchandisePresenter : BasePresenter<INewEditMerchandiseViewModel>
    {
        private MerchandiseBC _bc;

        public NewEditMerchandisePresenter()
        {
            _bc = new MerchandiseBC();
        }
        protected override void WireupEventHandles()
        {

        }

        public void Save()
        {
            bool ok = true;
            var error = ValidateModel();
            if (error.Count() > 0)
            {
                XtraMessageBox.Show(string.Join("\n", error.ToArray()), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                var dto = new MerchandiseDTO()
                {
                    CategoryId = Model.CategoryId == -1 ? null : Model.CategoryId,
                    Madein = Model.Madein,
                    MerchandiseName = Model.MerchandiseName,
                    TradeMark = Model.TradeMark,
                    Unit = Model.Unit
                };
                if (!Model.IsEdit)
                    _bc.AddMerchandise(dto);
                else
                    _bc.UpdateMerchandise(Model.Id, dto);
            }
            catch
            {
                ok = false;
            }
            finally
            {
                Model.MerchandiseSaved(ok, Model.IsEdit);

            }
        }

        private IEnumerable<string> ValidateModel()
        {
            if (string.IsNullOrEmpty(Model.MerchandiseName))
                yield return "Yêu cầu nhập tên mặt hàng";
            if (string.IsNullOrEmpty(Model.Unit))
                yield return "Yêu cầu nhập đơn vị tính";

        }




        public void LoadCategoryList()
        {
            Model.Categories = _bc.GetCategoryList().ToList();
        }
    }
}
